<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <th:block th:include="include :: header('采集数据点位管理')" />
    <th:block th:include="include :: layout-latest-css" />
    <th:block th:include="include :: ztree-css" />
    <style>
        .modal-dialog .item-wrap{ display: flex; margin-bottom: 10px; align-items: center; }
        .modal-dialog .item-wrap .item-key{ width: 90px; text-align: right; padding-right: 10px; }
        .modal-dialog .item-wrap .azdw-select{ flex: 1; margin-right: 5px; }
        .modal-dialog .control-label{ margin: 6px 0 2px 0; }
        .table-point .btn{ margin: 0 5px; }
        .table-point .control-label{ margin: 15px 0 5px 0; }
    </style>
</head>
<body>


<div class="ui-layout-west">
    <div class="box box-main">
        <div class="box-header">
            <div class="box-title">
                <i class="fa icon-grid"></i>
                <span>场景结构</span>
            </div>
            <div class="box-tools pull-right">
                <a type="button" class="btn btn-box-tool" href="#" onclick="dept()" title="管理部门"><i class="fa fa-edit"></i></a>
                <button type="button" class="btn btn-box-tool" id="btnExpand" title="展开" style="display:none;"><i class="fa fa-chevron-up"></i></button>
                <button type="button" class="btn btn-box-tool" id="btnCollapse" title="折叠"><i class="fa fa-chevron-down"></i></button>
                <button type="button" class="btn btn-box-tool" id="btnRefresh" title="刷新部门"><i class="fa fa-refresh"></i></button>
            </div>
        </div>
        <div class="ui-layout-content">
            <div id="tree" class="ztree"></div>
        </div>
    </div>
</div>

<div class="ui-layout-center">
    <div class="container-div">
        <!-- 表单查询条件 -->
        <form id="scene-form">
            <input type="hidden" id="sceneId" name="sceneId" value="3" />
        </form>
        <div class="btn-group-sm" id="toolbar" role="group">
            <a class='btn btn-success' href='javascript:;' onclick='addScenePoint()' title="新增">
                <i class="fa fa-plus"></i>
                <span>新增采集数据点位</span>
            </a>
        </div>
        <!-- 右侧场景表格 -->
        <div class="col-sm-12 select-table table-point">
            <!-- 这是表格列表显示 -->
             <table id="bootstrap-table"></table>
        </div>

    </div>
</div>

<!-- 这是编辑监测点的弹框 -->
<div class="modal " id="editor-point-dialog" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated flipInY">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">修改采集监测点名称</h4>
            </div>

            <div class="modal-body">
                <input type="hidden" name="sceneId" id="current-point-id" value="" />
                <div class="control-label">采集监测点名称：</div>
                <div class="input-wrap">
                    <input class="form-control" type="text" name="sceneName" id="new-point-name"  placeholder="请输入新的名称" maxlength="30"
                    />
                </div>
                <div class="control-label">当前的采集监测点名称：</div>
                <div class="input-wrap">
                    <input class="form-control" readonly="true" type="text" id="current-point-name" value="" />
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitChangePointInfo()">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 这是场景下新增采集数据点的弹框 -->
<div class="modal " id="add-point-dialog" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content animated flipInY">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">新增采集数据点</h4>
            </div>

            <div class="modal-body">
                <div class="item-wrap">
                    <span class="item-key">采集数据点:</span>
                    <select name="pointId" id="point-select" style="width:200px" class="form-control"></select>
                </div>
                <div class="item-wrap">
                    <span class="item-key">上限值:</span>
                    <input type="text" class="form-control" style="width:200px" disabled="true" name="upperLimit" id="upperLimit">
                </div>

                <div class="item-wrap ">
                    <span class="item-key">下限值:</span>
                    <input type="text" class="form-control" style="width:200px" disabled="true" name="lowerLimit" id="lowerLimit">
                </div>
                <div id="element2"  class="item-wrap ">
                    <span class="item-key">安装点位:</span>
                    <select name="dev_azdw1_id" id="dev_azdw1_select" class="first form-control azdw-select" data-index="1"></select>
                    <select name="dev_azdw2_id" id="dev_azdw2_select" class="second form-control azdw-select" data-index="2"></select>
                    <select name="dev_azdw3_id" id="dev_azdw3_select" class="third form-control azdw-select" data-index="3"></select>
                    <select name="dev_azdw4_id" id="dev_azdw4_select" class="fourth form-control azdw-select" data-index="4"></select>
                    <select name="dev_azdw5_id" id="dev_azdw5_select" class="fifth form-control azdw-select" data-index="5"></select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="submitAddScenePoint()">保存</button>
            </div>
        </div>
    </div>
</div>


<!-- 底部静态引入 -->
<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: ztree-js" />
<script th:inline="javascript">
    var checkSceneTreeInfo = null ;// 选中的左侧树的场景节点信息
    var checkPointInfo = null; // 选中的右侧监测点的信息

    $(function() {

        var panehHidden = false;
        if ($(this).width() < 769) {
            panehHidden = true;
        }
        $('body').layout({ initClosed: panehHidden, west__size: 185 });
        // 回到顶部绑定
        if ($.fn.toTop !== undefined) {
            console.log('toTop 22 ========================= ')
            var opt = {
                win:$('.ui-layout-center'),
                doc:$('.ui-layout-center')
            };
            $('#scroll-up').toTop(opt);
        }
        // 查询场景左侧树
        querySceneTree();
        // 查询场景表格列表
        queryScenePointList();
        // 初始化调用设备选择下拉框，第一级筛选
        initAZDWselect();
        // 初始化调用根据条件筛选监测点（弹框里的监测点下拉框）
        queryPointSelect();

        // 选择安装点位 select 下拉框的时候触发方法
        $('.azdw-select').change(function(e){
            console.log(` change e ============================= `)
            console.log(e)
            console.log($(this))
            // $('.azdw-select').val("");
            var getSelectIndex = $(this).attr("data-index") || 1;
            var maxSelectIndex = 6;
            var nextSelectIndex = Number(getSelectIndex)+1;
            let startIndex = getSelectIndex;
            while (startIndex<maxSelectIndex){
                startIndex++;
                $(`#dev_azdw${startIndex}_select`).val("").text("请选择")
            }
            // 获取下一级select 下拉框的数据，只有存在下一级的时候，在需要调用设置 option 方法
            if(nextSelectIndex<maxSelectIndex){
                initAZDWselect(nextSelectIndex);
            }
            // 调用根据条件筛选监测点
            queryPointSelect();
        })
        // 选择完检测点之后，需要根据点击设置上下限的值
        $("#point-select").change(function(e){
            console.log(' point-select e ========================== ')
            console.log(e)
            console.log( 'html=> '+ $(this).find("option:selected").html() )
            var $checkOption =  $(this).find("option:selected");
            var getLower = "";
            var getUpper = "";
            if($checkOption){
                getLower = $checkOption.attr("data-lower");
                getUpper = $checkOption.attr("data-upper");
            }
            $("#upperLimit").val(getLower=="null"?"":getLower)
            $("#lowerLimit").val(getUpper=="null"?"":getUpper)
        })
    });

    // 请求加载右侧检测点数据，并用表格渲染
    function queryScenePointList() {
        var options = {
            url: "/youtian/scene-category/scencePointlist",
            method:'get',
            sortable:false, // 不使用排序
            // rowStyle:onRowStyle,// 根据条件渲染表格的行样式
            columns: [
                /*{
                    field: 'selectItem',
                    width: '60',
                    widthUnit: 'px',
                    align: "center",
                    radio: true
                },*/
                {
                    field: 'pointName',
                    title: '采集数据点位',
                    align: "center"
                },
                {
                    field: 'sceneName',
                    title: '所属区',
                    align: "center"
                },
                {
                    field: 'deptName',
                    title: '所属单位',
                    align: "center"
                },
                {
                    field: 'dataState',
                    title: '状态',
                    align: "center",
                    formatter: function(value, row, index) {
                        if( $.trim(value) == "正常"){
                            return `<span style='color: #f00; font-weight: bold;'>${value}</span>`
                        }
                        return value
                    }
                },
                {
                    field: 'lowerLimit',
                    title: '下限',
                    align: "center"
                },
                {
                    field: 'upperLimit',
                    title: '上限',
                    align: "center"
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var rowJson = JSON.stringify(row);
                        // console.log(`rowJson : ${rowJson}`)
                        var actions = [];
                        actions.push(`<a class='btn btn-primary btn-xs' href='javascript:;' onclick='showEditorDialog(${rowJson})' title="编辑"><i class='fa fa-edit'></i><span>编辑</span></a>`)
                        actions.push(`<a class="btn btn-danger btn-xs" href="javascript:;" onclick='deletePoint(${rowJson})' title='删除'><i class="fa fa-remove"></i><span>删除</span></a>`)
                        return actions.join('');
                    }
                }
            ]
        }
        //初始化监测点表格
        $.table.init(options);
    }

    function onRowStyle(row, index){
        if( $.trim(row.dataState) == "异常"){
            return {css:{"background-color":"rgba(255,0,0,0.7)"}};
        }
        return ""
    }

    // 请求加载左侧树方法
    function querySceneTree() {
        // var url = "/youtian/scene-category/list"
        var url = "/youtian/scene-category/ztree"

        // 上线之后注释，暂时测试使用
       /* $.ajax({
            method: "get",
            url: url,
            data: {pageNum:1,pageSize:1001},
            success: function (res) {
                var rowsArr = []
                if(res.code==0){
                    for (let i = 0; i < res.rows.length; i++) {
                        res.rows[i].id= res.rows[i].sceneId;
                        res.rows[i].pId= res.rows[i].parentId;
                        res.rows[i].name= res.rows[i].sceneName;
                        res.rows[i].title= res.rows[i].sceneName;
                        res.rows[i].checked= false;
                        res.rows[i].label= null
                        res.rows[i].open= false;
                        res.rows[i].nocheck= false;
                        rowsArr.push(res.rows[i]);
                    }
                }
                console.log(`rowsArr 222 ============================== `)
                console.log(rowsArr)
                $.fn.zTree.init($("#tree"), {callback: {
                        onClick: sceneTreeOnClick
                    }}, rowsArr);
            }
        })

*/
        // let ab = $.tree.init( $('#tree'), options,zNodes);

        // 上线之后放开，init调用options
        // 默认配置，只能 get 请求
        var options = {
            url:url,
            expandLevel: 2,
            onClick : sceneTreeOnClick
        }
        $.tree.init(options);
    }

    // 点击左侧场景树，触发查询方法
    function sceneTreeOnClick(event, treeId, treeNode) {
        checkSceneTreeInfo = treeNode;
        console.log('event, treeId, treeNode 333 ======= ')
        console.log(event, treeId, treeNode)
        $('#sceneId').val(treeNode.id);
        //调用查询方法
        $.table.search();
    }

    // 新增数据检测点位
    function addScenePoint(){
        console.log('左侧树下新增~')
        // 2、 左侧树下，添加新场景
        var msg =""
        if(!checkSceneTreeInfo){
            msg = "请您先选中左侧菜单，再添加新的检测点~";
        }
        /*if(checkSceneTreeInfo&&checkSceneTreeInfo.level<3){
            msg = "只能在末层级，才能添加监测点";
        }*/
        if(msg){
            $.modal.msgError(msg);
            return;
        }
        // 每次显示都需要重置，下拉框的内容, 重置完之后在显示弹框
        $('#point-select').val("")
        $('.azdw-select').val("")
        $("#upperLimit").val("")
        $("#lowerLimit").val("")
        // 展示添加监测点弹框
        $('#add-point-dialog').modal('show');
    }
    // 场景下新增采集监测点方法（发送请求）
    function submitAddScenePoint(){
        var getValue = $.trim($('#point-select').val());
        if (getValue =='') {
            $.modal.msgError("请选择新增的监测点");
            return
        }
        let params = {
            sceneId: checkSceneTreeInfo.id,
            pointId: getValue
        };
        console.log( " data params 123 ========================= ");
        console.log(params);
        $.ajax({
            method: "post",
            url: "/youtian/scene-point",
            data: JSON.stringify(params),
            dataType: "json",
            contentType: "application/json",
            success: function (res) {
                if(res.msg){
                    $.modal.msgSuccess(res.msg);
                }
                // 提交成功，刷新表格，并把input框里的值，清空。
                if(res.code ==0){
                    $.table.search();
                    $('#add-point-dialog').modal('hide');
                }
            }
        });
    }

    // 点击右侧的编辑按钮，展示编辑dialog弹框
    function showEditorDialog(jsonObj){
        checkPointInfo = jsonObj;
        $('#new-point-name').val('')
        $('#current-point-name').val(jsonObj.pointName)
        $('#current-point-id').val(jsonObj.pointId)
        $('#editor-point-dialog').modal('show');
    }

    // 点击右侧表格的编辑按钮，弹层编辑完之后， 确定保存
    function submitChangePointInfo() {
        var getPointName = $.trim($('#new-point-name').val());
        if (getPointName =='') {
            console.log(`getName : ${getPointName}`)
            $.modal.msgError("请输入采集监测点名称");
            return;
        }
        // 获取当前的检测点 id 值
        var getPointId = $.trim($('#current-point-id').val());
        let params = {
            SourceTag: getPointId,
            Description: getPointName
        }

        $.ajax({
            method: "post",
            url: `/gzmx_tag_current/gzmx_tag_current/edit?SourceTag=${getPointId}&Description=${getPointName}`,
            success: function (res) {
                if(res.msg){
                    $.modal.msgSuccess(res.msg);
                }
                // 提交成功，刷新表格，并把input框里的值，清空。
                if(res.code ==0){
                    $.table.refresh();
                    $('#editor-point-dialog').modal('hide');
                }
            }
        });
    }
    // 点击右侧表格的删除按钮，弹层询问是否删除
    function deletePoint(pointInfoJson){
        var content = `您确认要删除"${pointInfoJson.pointName?pointInfoJson.pointName:"-"}"，该采集数据点位吗？`;
        // 点击确认，删除对应的场景，并刷新表格
        $.modal.confirm(content,function(isOk){
            console.log(`res,err ======== `)
            console.log(isOk)
            let params = {
                pointId: pointInfoJson.pointId,
                sceneId: pointInfoJson.sceneId,
                id: pointInfoJson.scenePointId,
            };
            $.ajax({
                url: `/youtian/scene-point/remove`,
                dataType: "json",
                headers: { "Content-Type": "application/json" },
                type: "post",
                data: JSON.stringify(params),
                success: function (res) {
                    if(res.msg){
                        $.modal.msgSuccess(res.msg);
                    }
                    // 提交成功，刷新表格，并把input框里的值，清空。
                    if(res.code == 0){
                        $.table.search();
                        $('#editor-point-dialog').modal('hide');
                    }
                }
            })
        });
    }
     // 安装点位筛选 selectd 的方法。
    function initAZDWselect(nextSelectIndex){
        var params ={
            "jb" : 1
        }
        nextSelectIndex = nextSelectIndex?nextSelectIndex:1;
        var $nextSelect = $(`#dev_azdw${nextSelectIndex}_select`);
        if(nextSelectIndex>1){
            params= {
                fdwdm : $(`#dev_azdw${nextSelectIndex-1}_select`).val()
            }
        }
        $.ajax({
            type: "post",
            url: "/gzmx_scdw/gzmx_scdw/list",
            data: params,
            success: function(res) {
                console.log(' 生产点位 /gzmx_scdw/gzmx_scdw/list res');
                console.log(res);
                console.log($nextSelect);
                var optionHTML = `<option value="">请选择</option>`
                for (let i = 0; i < res.length; i++) {
                    optionHTML+=`<option value="`+res[i].id+`">`+res[i].dwmc+`</option>`
                }
                $nextSelect.html(optionHTML);
            },
            error: function(error) {
                $.modal.alertWarning(error);
            }
        });
    }


    // 根据条件，筛选符合条件的监测点信息
    function queryPointSelect() {
        $("#point-select").html(`<option value="">请选择</option>`);
        let data = {
            deptId: null,
            ejdw_id: $("#dev_azdw1_select").val(),
            dw_3_id: $("#dev_azdw2_select").val(),
            dw_4_id: $("#dev_azdw3_select").val(),
            dw_5_id: $("#dev_azdw4_select").val(),
            dw_6_id: $("#dev_azdw5_select").val()
        };
        console.log(data, "data");
        $.ajax({
            method: "POST",
            url: "/gzmx_tag/gzmx_tag/list",
            data: data,
            success: function (res) {
                console.log(res, "data res");
                var optionHTML=`<option value="">请选择</option>`;
                for (let i = 0; i < res.rows.length; i++) {
                    var item = res.rows[i];
                    optionHTML+=`<option value="${item.sourceTag}" data-lower="${item.min_value}" data-upper="${item.max_value}" >${item.description}</option>`
                }
                $("#point-select").html(optionHTML);
                $("#upperLimit").val("")
                $("#lowerLimit").val("")
            }
        });
    }

</script>

</body>
</html>